package com.chang.bootplus.config.security;



import com.chang.bootplus.entity.MatrixUser;
import com.chang.bootplus.service.MatrixUserService;
import org.bouncycastle.pqc.math.linearalgebra.Matrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {


	@Autowired
	MatrixUserService userService;

	@Override
	public UserDetails loadUserByUsername(@RequestBody String username) throws UsernameNotFoundException {

		MatrixUser user= userService.getByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户名或密码不正确");
		}

		return new AccountUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));

	}

	/**
	 * 获取用户权限信息（角色、菜单权限）
	 * @param userId
	 * @return list
	 */
	public List<GrantedAuthority> getUserAuthority(Long userId){

		// 角色(ROLE_admin)、菜单操作权限 sys:user:list
		String authority = userService.getUserAuthorityInfo(userId);
// ROLE_admin,ROLE_normal,sys:user:list,....

		// 将当前的 格式化字符串转化为权限集合
		return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
	}

}
